package com.example.shop_2207.fragment

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.shop_2207.entity.CarEntityResult
import com.example.shop_2207.entity.ResultEntity
import com.example.shop_2207.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.get
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class CarViewModel:BaseViewModel() {
    val selectSuccess = MutableLiveData<CarEntityResult>()
    val selectFail = MutableLiveData<String>()

    fun selectCar(){
        viewModelScope.launch {
            try {
               val result = apiServer.selectCar()
               selectSuccess.value = result
            }catch (e:Exception){
                selectFail.value = e.message
            }
        }
    }

    val addSuccess = MutableLiveData<ResultEntity>()
    val addFail = MutableLiveData<String>()

    fun addCar(count:Int,goods_id:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Int>()
                map["count"] = count
                map["goods_id"] = goods_id
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.addCar(body)
                addSuccess.value = result
            }catch (e:Exception){
                addFail.value = e.message
            }
        }
    }

    val deleteSuccess = MutableLiveData<ResultEntity>()
    val deleteFail = MutableLiveData<String>()
    fun deleteCar(ids:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map["ids"] = ids
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.deleteCar(body)
                deleteSuccess.value = result
            }catch (e:Exception){
                deleteFail.value = e.message
            }
        }
    }
}